#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

static void print_ids(const char * info) {
    pthread_t  tid = pthread_self();
    printf("%s tid [0x%04x]\n", info, (unsigned int)tid & 0xffff);
}

volatile int counter = 0;

static void * thread_function(void * arg) {
    pthread_t tid = pthread_self();

    while (counter < 50) {
        printf("thread[0x%04x] counter: %d\n", (unsigned int)tid & 0xffff, counter++);
    }

    printf("thread[0x%04x] exit\n", (unsigned int)tid & 0xffff);
    return NULL;
}

int main() {
    const int t_num = 5;

    pthread_t ntid[t_num];
    for( int i = 0 ;i < t_num; ++i){
        assert(0 == pthread_create(ntid + i, NULL, thread_function, NULL));
    }

    for(int i = 0; i < t_num; ++i){
        void * retval = 0;
        assert(0 == pthread_join(ntid[i], &retval));
    }
    
    print_ids("main thread:");
    printf("main thread exit\n");

    return 0;
}

